// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: Markus Gutschke

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "check.h"
#include "http.h"
#include "poll_printer_reg.h"
#include "stringprintf.h"


struct JSON *pollPrinterRegistration(const struct HashMap *reg,
                                     const char *client_id) {
  const struct JSON *polling_url, *token_duration;
  check((polling_url = (const struct JSON *)
         getFromHashMap(reg, "polling_url")) &&
        polling_url->type == J_STRING);
  check((token_duration = (const struct JSON *)
         getFromHashMap(reg, "token_duration")) &&
        token_duration->type == J_STRING);
  char *url = stringPrintf(NULL,
                           "%s%s", polling_url->str,
                           client_id);
  sleep(4);
  for (time_t tmo = time(0) + atoi(token_duration->str); time(0) - tmo < 0; ) {
    const char *body;
    check(body = GET(url, NULL));

    // Parse response
    struct JSON *json = newJSON(body);
    free((void *)body);

    // Verify that the registration was successful
    check(json->type == J_OBJECT);
    const struct JSON *success;
    check((success = (const struct JSON *)
           getFromHashMap(&json->obj, "success")) &&
          (success->type == J_TRUE || success->type == J_FALSE));
    if (success->type == J_TRUE) {
      free(url);
      return json;
    }

    deleteJSON(json);
    sleep(30);
  }
  free(url);
  return NULL;
}
